{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"/>

    <title>MRC编程</title>
    <link rel="icon" href="{% static 'img/mrc_logo.png' %}" type="img/x-ico" />
    <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}">
    <link rel="stylesheet" href="{% static 'js/layer/theme/default/layer.css' %}">
    <link rel="stylesheet" href="{% static 'js/jquery-ui-1.12.1.custom/jquery-ui.min.css' %}">
    <link rel="stylesheet" href="{% static 'css/action_api.css' %}">
    <link rel="stylesheet" href="{% static 'css/index.css' %}">
    <script src="{% static 'js/jquery.min.js' %}"></script>
    <script src="{% static 'js/toolbox/loadxml.js' %}"></script>

    <!-- ******************debug model*********************** -->
{#    <script src="{% static 'blockly/blockly_uncompressed_vertical.js' %}"></script>#}
{#    <script src="{% static 'blockly/msg/messages.js' %}"></script>#}
{#    <script src="{% static 'blockly/msg/js/zh-hans.js' %}"></script>#}
{##}
{#    <script src="{% static 'blockly/blocks_vertical/vertical_extensions.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_common/math.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_common/text.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_common/colour.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/control.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/event.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/motion.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/looks.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/procedures.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/operators.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/pen.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/sound.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/sensing.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/data.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/inout.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/default_toolbox.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/customs.js' %}"></script>#}
{#    <script src="{% static 'blockly/blocks_vertical/servo.js' %}"></script>#}
{##}
{#    <script src="{% static 'blockly/generators/arduino.js' %}"></script>#}
{#    <script src="{% static 'blockly/generators/arduino/logic.js' %}"></script>#}
{#    <script src="{% static 'blockly/generators/arduino/math.js' %}"></script>#}
{#    <script src="{% static 'blockly/generators/arduino/control.js' %}"></script>#}
{#    <script src="{% static 'blockly/generators/arduino/text.js' %}"></script>#}
{#    <script src="{% static 'blockly/generators/arduino/data.js' %}"></script>#}
{#    <script src="{% static 'blockly/generators/arduino/inout.js' %}"></script>#}
{#    <script src="{% static 'blockly/generators/arduino/customs.js' %}"></script>#}
{#    <script src="{% static 'blockly/generators/arduino/servo.js' %}"></script>#}
{#    <script src="{% static 'blockly/generators/arduino/motion.js' %}"></script>#}
{##}
{#    <script type="application/javascript" src="{% static 'blockly/generators/javascript.js' %}"></script>#}
{#    <script type="application/javascript" src="{% static 'blockly/generators/javascript/logic.js' %}"></script>#}
{#    <script type="application/javascript" src="{% static 'blockly/generators/javascript/math.js' %}"></script>#}
{#    <script type="application/javascript" src="{% static 'blockly/generators/javascript/motion.js' %}"></script>#}
{#    <script type="application/javascript" src="{% static 'blockly/generators/javascript/control.js' %}"></script>#}
{#    <script type="application/javascript" src="{% static 'blockly/generators/javascript/text.js' %}"></script>#}
{#    <script type="application/javascript" src="{% static 'blockly/generators/javascript/data.js' %}"></script>#}
{#    <script type="application/javascript" src="{% static 'blockly/generators/javascript/inout.js' %}"></script>#}
{#    <script type="application/javascript" src="{% static 'blockly/generators/javascript/servo.js' %}"></script>#}
{#    <script type="application/javascript" src="{% static 'blockly/generators/javascript/customs.js' %}"></script>#}
    <!-- *********************end debug****************************** -->


    <!-- ************************release model************************************* -->
      <script type="application/javascript" src="{% static 'lib/blockly_compressed_vertical.js' %}"></script>
      <script src="{% static 'lib/blocks_compressed.js' %}"></script>
      <script type="application/javascript" src="{% static 'lib/blocks_compressed_vertical.js' %}"></script>
      <script type="application/javascript" src="{% static 'lib/arduino_compressed.js' %}"></script>
      <script type="application/javascript" src="{% static 'lib/javascript_compressed.js' %}"></script>
      <script src="{% static 'msg/messages.js' %}"></script>
      <script src="{% static 'msg/js/zh-hans.js' %}"></script>
    <!-- ************************** end release********************************** -->








    {#  <script src="{% static 'js/Blob.js'%}"></script>#}
    {#  <script src="{% static 'js/spin.js' %}"></script>#}
    <script src="{% static 'js/FileSaver.min.js' %}"></script>
    <script src="{% static 'js/blockly_helper.js' %}"></script>
    <script src="{% static 'js/mikuCanvasImageUtil.js' %}"></script>
    <script src="{% static 'js/bootstrap.min.js' %}"></script>
    <script src="{% static 'js/jszip.min.js' %}"></script>

    <script src="{% static 'js/layer/layer.js' %}"></script>
    <script src="{% static 'js/jquery-ui-1.12.1.custom/jquery-ui.min.js' %}"></script>
    <script src="{% static 'js/action_api.js' %}"></script>
    <script src="{% static 'js/spark-md5.js' %}"></script>
    <script src="{% static 'js/tool.js' %}"></script>
    <script src="{% static 'js/uploads-core.js' %}"></script>
    <script src="{% static 'js/index.js' %}"></script>
</head>

<body onload="toolboxReady()">

<div class="meta-nav">
    <nav class="navbar navbar-top navbar-inverse">
        <div class="container-fluid">
            <div class="">
                <div class="navbar-header">
                    <a class="navbar-brand" href="#">
                        <img alt="Brand" src="{% static 'img/mrc_logo.png' %}" style="height: 90%">
                    </a>
                </div>
                <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                    <ul class="nav navbar-nav navbar-left navbar-nav-top">
                        <li>
                            <a href="#" class="download dropdown-toggle" data-toggle="dropdown" aria-haspopup="true"
                               aria-expanded="false">文件<span class="caret"></span></a>
                            <ul class="dropdown-menu">
                                <li><a href="javascript:void(0)" onclick="new_empty_project()">新建空工程</a></li>
                                <li><a href="javascript:void(0)" onclick="save()">保存工程</a></li>
                                <li><a href="javascript:void(0)" id="fakeload">加载工程</a>
                                    <input type="file" id="load" accept="mt" style="display: none;"/>
                                </li>
                                <li class="dropdown-submenu">
                                  <a href="#" id="show_history">历史记录<span></span></a>
                                  <ul class="dropdown-menu">
                                    <li class="board-connect">
                                        <i class="glyphicon glyphicon-ok" style="display: none"></i>
                                        <a href="javascript:void(0)" >
                                            <ul class="history">
                                                <!--<li> <a href="#" data-toggle="modal" data-target="#myModal03">2018.3.13</a><button data-toggle="modal" data-target="#myModal04">删除</button></li>-->
                                                <!--<li> <a href="#" data-toggle="modal" data-target="#myModal03">2018.3.12</a><button data-toggle="modal" data-target="#myModal04">删除</button></li>-->
                                                <!--<li> <a href="#" data-toggle="modal" data-target="#myModal03">2018.3.11</a><button data-toggle="modal" data-target="#myModal04">删除</button></li>-->
                                                <!--<li> <a href="#" data-toggle="modal" data-target="#myModal03">2018.3.10</a><button data-toggle="modal" data-target="#myModal04">删除</button></li>-->
                                            </ul>
                                        </a>
                                    </li>
                                  </ul>
                                </li>
                            </ul>
                        </li>
                        <li>
                            <a href="javascript:void(0)" class="dropdown-toggle" data-toggle="dropdown" aria-haspopup="true"
                               aria-expanded="false">编辑<span class="caret"></span></a>
                            <ul class="dropdown-menu">
{#                                <li class="dropdown-submenu" style="display: block">#}
{#                                    <a href="#">编程模式<span></span></a>#}
{#                                    <ul class="dropdown-menu">#}
{#                                        <li class="arduino-control-mode"><i class="glyphicon glyphicon-ok" style="display: block"></i><a href="javascript:void(0)" value="0" onclick="arduino_control_mode(this)">MRC离线控制模式</a></li>#}
{#                                        <li class="arduino-control-mode"><i class="glyphicon glyphicon-ok" style="display:none"></i><a href="javascript:void(0)" value="1" onclick="arduino_control_mode(this)">MRC在线控制模式</a>#}
{#                                        </li>#}
{##}
{#                                    </ul>#}
{#                                </li>#}
                                <li class="dropdown-submenu">
                                    <a href="#">板子选择<span></span></a>
                                    <ul class="dropdown-menu">
                                        <li class="board"><i class="glyphicon glyphicon-ok" style="display: block"></i><a href="javascript:void(0)" value="arduino:avr:nano:cpu=atmega328" onclick="select_board(this)">MRC</a></li>
                                        <li class="board"><i class="glyphicon glyphicon-ok" style="display: none"></i><a href="javascript:void(0)" value="arduino:avr:nano:cpu=atmega328" onclick="select_board(this)">arduino nano</a></li>
                                        <li class="board"><i class="glyphicon glyphicon-ok" style="display:none"></i><a href="javascript:void(0)" value="arduino:avr:uno" onclick="select_board(this)">arduino uno</a>
                                        </li>
                                    </ul>
                                </li>
                            </ul>
                        </li>
                        <li>
                            <a href="#" class="download dropdown-toggle" data-toggle="dropdown" aria-haspopup="true"
                               aria-expanded="false">帮助<span class="caret"></span></a>
                            <ul class="dropdown-menu">
                                <li><a href="javascript:void(0)" data-toggle="modal" data-target="#myModal">关于</a></li>
                                <li><a href="javascript:void(0)" data-toggle="modal" data-target="#myModal02">授权同意书</a></li>

                            </ul>
                        </li>

                    </ul>
                    <div class="navbar-right">
                      <h4 id="blockly_mode" style="display: block">离线控制模式</h4>
                    </div>
                </div>
            </div>
        </div>
    </nav>
</div>


<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" style="margin-top:20%">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <img alt="Brand" src="{% static 'img/mrc_logo.png' %}">
            </div>
            <div class="modal-body">
                <p>本软件所属公司是广州艾考教育科技有限公司</p>
                <p>名人才编程 v1.0.2版本</p>
                <p>开发人员 Jack He、Kellen zhang</p>
                <p>MRC编程软件最后解释权所属于广州艾考教育科技有限公司</p>
            </div>
        </div>
    </div>
</div>

<!--授权书弹窗-->
<div class="modal fade" id="myModal02" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" >
    <div class="modal-dialog" role="document" style="width:1200px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <img alt="Brand" src="{% static 'img/mrc_logo.png' %}">
            </div>
            <div style="padding: 20px 40px;">
                <p>授权书</p>
                <p>信息授权协议（以下简称“本协议”）是广州艾考教育科技有限公司（以下简称“艾考”）在使用”MetasLab-MRC编程平台（以下简称“平台”）时，与用户 (以下简称“您”)就个人信息授权使用所订立的合约。</p>
                <p>您通过应用授权页面点击确认，即表示您同意接受本协议的全部约定内容以及与本协议有关的已经发布或将来可能发布的各项规则、页面展示、操作流程、公告或通知（以下统称“规则 ” ）。</p>
                <p>在接受本协议之前，请您仔细阅读本协议的全部内容 （特别是以粗体下划线标注的内容）。如果您不同意本协议的任意内容，或者无法准确理解该条款的含义，请不要进行任何操作。</p>
                <p>一、您同意并授权艾考将您的个人信息提供给支付宝（中国）网络技术有限公司（以下简称“支付宝”），深圳市腾讯计算机系统有限公司（以下简称“腾讯”），以用于您向平台第三方登录操作。</p>
                <p>二、本协议中的个人信息，包括但不限于： </p>
                <p>1、您的个人电脑/设备信息；</p>
                <p>2、您的课程设计内容；</p>
                <p>3、您在”平台“留存的操作信息，包括但不限于操作日志；</p>
                <p>三、您同意本协议中的授权不可撤回或撤销。</p>
                <p>四、您同意，因履行本协议发生纠纷的，任何一方应向被告住所地人民法院提起诉讼。</p>
                <p></p>
            </div>
        </div>
    </div>
</div>
<!--启动页面授权书-->
<div class="attorney" style="display: none">
    <div class="attorneyin">
        <img alt="Brand" src="{% static 'img/mrc_logo.png' %}" class="attlogo" style="display: block;margin: 0 auto">
        <h3 class="atttitle">授权书</h3>
        <p>信息授权协议（以下简称“本协议”）是广州艾考教育科技有限公司（以下简称“艾考”）在使用”MetasLab-MRC编程平台（以下简称“平台”）时，与用户 (以下简称“您”)就个人信息授权使用所订立的合约。</p>
        <p>您通过应用授权页面点击确认，即表示您同意接受本协议的全部约定内容以及与本协议有关的已经发布或将来可能发布的各项规则、页面展示、操作流程、公告或通知（以下统称“规则 ” ）。</p>
        <p>在接受本协议之前，请您仔细阅读本协议的全部内容 （特别是以粗体下划线标注的内容）。如果您不同意本协议的任意内容，或者无法准确理解该条款的含义，请不要进行任何操作。</p>
        <p>一、您同意并授权艾考将您的个人信息提供给支付宝（中国）网络技术有限公司（以下简称“支付宝”），深圳市腾讯计算机系统有限公司（以下简称“腾讯”），以用于您向平台第三方登录操作。</p>
        <p>二、本协议中的个人信息，包括但不限于： </p>
        <p>1、您的个人电脑/设备信息；</p>
        <p>2、您的课程设计内容；</p>
        <p>3、您在”平台“留存的操作信息，包括但不限于操作日志；</p>
        <p>三、您同意本协议中的授权不可撤回或撤销。</p>
        <p>四、您同意，因履行本协议发生纠纷的，任何一方应向被告住所地人民法院提起诉讼。</p>
        <!--<p><input type="checkbox" class="agreed" value=""/> 我已阅读并协议同意授权</p>-->
        <p class="attobut"><input type="button" value="同意" class="agreedin" agree="1"/><input type="button" value="不同意" agree="2"/></p>
    </div>
</div>
<!--历史记录提示-->
<div class="modal fade historymodal" id="myModal03" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" style="margin-top:20%">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
          aria-hidden="true">&times;</span></button>
        <img alt="Brand" src="{% static "img/mrc_logo.png"%}">
      </div>
      <div class="modal-body">
        <p class="hisp">是否打开积木<span class="histimer"></span>历史记录，请注意先保存当前工程</p>

          <div class="historybtn">
               <button class="historyyes" data-dismiss="modal" aria-label="Close">打开</button><button class="historyno" data-dismiss="modal" aria-label="Close">不打开</button>
          </div>
      </div>
    </div>
  </div>
</div>
<!--是否删除历史记录-->
<div class="delehis">
    <div class="modal fade historymodal" id="myModal04" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" style="margin-top:20%">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span
              aria-hidden="true">&times;</span></button>
            <img alt="Brand" src="{% static 'img/mrc_logo.png' %}">
          </div>
          <div class="modal-body">
            <p class="deletehisp">是否删除历史记录<span class="histimer"></span></p>
              <div class="historybtn">
                   <button class="deletehistoryyes" data-dismiss="modal" aria-label="Close">是</button><button class="historyno" data-dismiss="modal" aria-label="Close">否</button>
              </div>
          </div>
        </div>
      </div>
    </div>
</div>
<div class="">
    <div class="">
        <div class="col-md-4 col-sm-12 left-contain" style="padding-right: 0px;">
            <div class="img-block">
                <div class="pre-img-block">
                    <div class="pre-img-head">
                        <div class="icon-1"><img src="{% static 'img/fangda.png' %}" style="float:left">
                            <p style="float:left;margin-left:10px;display:none" id="project_name"></p>
                        </div>
                        <div class="icon-2 character_start"><img src="{% static 'img/hongqi.png' %}"></div>
                        <div class="icon-2" id="character_reset"><img src="{% static 'img/tingzhi.png' %}"></div>
                    </div>
                    <div class="pre-img-show">
                        <div class="pre-img" id="operating-space">
                            <div data-role="BlockAction" id="action-block"><img src="{{ MEDIA_URL }}default_human/753c35deaf4b507f.png"></div>
                        </div>
                    </div>
                    <div class="pre-control">
                        <!--<span class="pre-c1" style="mameta-nav"rgin-left:10px"><img src="img/fuzhi.png"></span>-->
                        <span class="pre-c1"><img class="clearAreaBtn" src="{% static 'img/shanchu.png' %}"></span>
                        <span class="pre-c1"><img class="inAreaBtn" src="{% static 'img/da.png' %}"></span>
                        <span class="pre-c1"><img class="outAreaBtn" src="{% static 'img/xiao.png' %}"></span>
                    </div>
                </div>
            </div>
            <div class="coordinate">
                <span> x: 270 y: 47</span>
            </div>
            <div class="small-block">
                <div class="small-head">
                    <div style="float:left;margin-left:85px"><span>人物</span></div>
                    <div class="icon-6"><img src="{% static 'img/shangchuan.png' %}" class="myUploads" data-type="human"></div>
                    <!--<div class="icon-5"><img src="img/huabi.png"></div>-->
                    <div class="icon-4"><img src="{% static 'img/renwu.png' %}" class="openLibrary" data-type="human"></div>
                </div>
                <div class="small-foot">
                    <div class="icon-3"><img src="{% static 'img/tupian.png' %}" class="openLibrary" data-type="background"></div>
                    <div class="icon-6"><img src="{% static 'img/shangchuan.png' %}" class="myUploads" data-type="background"></div>
                </div>
                <div class="d-line"></div>
                <div class="small-show">
                    <div class="small-show-left">
                        <div class="bg-container myscrollbar">
                            <div class="bgk" data-clear="true">
                                <img src="{% static 'img/juxingkuang.png' %}" data-init="true">
                                <p>背景1</p>
                            </div>
                        </div>
                    </div>
                    <section class="small-show-right hm-container myscrollbar" id="changeImg">
                        <div class="change-img active"><img src="{{ MEDIA_URL }}default_human/753c35deaf4b507f.png" data-init="true"></div>
                        <div class="change-img"><img src="{{ MEDIA_URL }}default_human/5f1decb5302f330b.png" data-init="true"></div>
                    </section>
                </div>

            </div>
        </div>
        <div class="col-md-8 col-sm-12">
            <div>
                <div class="all right-content" id="box">
                    <h2 id="tabRow" class="Conbutleft">
                        <span style="background:#999;color:#fff;border-radius:6px 0px 0px 0px" id="tab_blocks">模块</span>
                        <span id="tab_arduino">触发</span>
                        <span style="margin:0;border-radius:0px 6px 0px 0px" id="tab_xml">XML</span>
                    </h2>
                    <h3 class="Conbutright">
                        <i><img src="{% static 'img/hong.png' %}" width="8%" class="connect_state" title="未连接到MRC"></i>
                        <button type="button" onclick="uploadClick()" id="arduino_upload_sketch">上传</button>
                        <button type="button" onclick="resetClick()" id="arduino_reset_sketch">重置</button>
                        <button onclick="discard()">删除</button>
                    </h3>
                    <a style="display:block;" id="content_blocks"></a>
                    <a>
                        <textarea id="content_arduino" class="content" readonly wrap="off"></textarea>
                    </a>
                    <a>
                        <textarea id="content_xml" class="content" wrap="off"></textarea>
                    </a>
                </div>

            </div>
        </div>
    </div>
</div>
<script>

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) === (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
    var csrftoken = getCookie('csrftoken');


    window.onresize = function () {
//  // changeFrameHeight();
        if ($(window).width() > 1000) {
            $(".left-contain,.right-content").height($(window).height() - 100);
        }
        ;

        var d_height = $(".small-block").height() - 36
        $(".d-line").css({"height": d_height, "top": "36px"})
        $(".small-show").css({"height": d_height});

    };
    $(window).resize();
    $(document).ready(function () {
        $(".left-contain,.right-content").height($(document).height() - 100);
        var d_height = $(".small-block").height() - 36;
        $(".d-line").css({"height": d_height, "top": "36px"})
        $(".small-show").css({"height": d_height});
    });

    function renderContent(count) {
        if (count == 1) {
            var arduinoTextarea = document.getElementById('content_arduino');
            arduinoTextarea.value = Blockly.Arduino.workspaceToCode(Blockly.mainWorkspace);
            arduinoTextarea.focus();
        }
        else if (count == 2) {
            var xmlTextarea = document.getElementById('content_xml');
            var xmlDom = Blockly.Xml.workspaceToDom(Blockly.mainWorkspace);
            var xmlText = Blockly.Xml.domToPrettyText(xmlDom);
            xmlTextarea.value = xmlText;
            xmlTextarea.focus();
        }

    }

    function tab(a) {
        var obox = document.getElementById(a);
        var spans = obox.getElementsByTagName('span');
        var divs = obox.getElementsByTagName('a');
        for (var i = 0; i < spans.length; i++) {
            spans[i].index = i;
            spans[i].onclick = function () {
                for (var i = 0; i < spans.length; i++) {
                    spans[i].style.background = '#fff';
                    spans[i].style.color = '#333'
                    divs[i].style.display = 'none'
                    renderContent(i)
                }
                this.style.background = '#999'
                this.style.color = '#fff'
                divs[this.index].style.display = 'block'
            }
        }
    }

    tab('box');
</script>
<script>
    /**
     * 关于块、背景、人物操作等方法与监听
     * 对外接口：
     *   ActionBlock: 块行动控制对象;
     *   createBackground: 创建背景方法, 用于背景添加的行内 js 调用;
     *                      createBackground(url:图片路径)
     *   createHuman:   创建人物方法, 用于背景人物的行内 js 调用;
     *                  createHuman(url:图片路径)
     *   getSaveConfig: 获取保存配置方法;
     *                  createHuman(string:是否返回字符串)
     *   initByConfig:  使用配置进行初始化方法;
     *                  initByConfig(config:getSaveConfig 返回的配置信息, string:是否传入字符串)
     * @author OJesusO
     */
    (function(areaObj, hmContainer, bgContainer, doc, W){
        //详细的块行动控制 http://ojesuso.gitee.io/action_api_class/
        //实例化 BlockAction, 用于控制块的行动操作
        W.ActionBlock = new BlockAction('#action-block', {
            images: getHumanImgsrc(),
            moveStep: 1,
        });
        function openDraggable () {
            ActionBlock.elementObj.draggable({
                grid: [1, 1],
                start: function(evt, ui) {
                    ActionBlock.transition = ui.helper.css('transition');
                    ui.helper.css({
                        transition: 'none',
                    });
                },
                drag: function(evt, ui) {
                },
                stop: function(evt, ui) {
                    ui.helper.css({
                        transition: ActionBlock.transition,
                    });
                },
                containment: 'parent',
            });
        }; openDraggable();

        //监听图片改变, 切换 ActionBlock 的背景 | 如果操作空间为空 放置内容
        hmContainer.on('click', '.change-img', function(){
            if (areaObj.find(ActionBlock.elementObj).length == 0) {
                ActionBlock.elementObj.appendTo(areaObj);
                openDraggable();
            }
            var src = $(this).find('img').attr('src');
            ActionBlock.changeImage(src, 150, 'auto');
            hmContainer.find('.change-img').not($(this)).removeClass('active');
            $(this).addClass('active');
        }).find('img').each(function(){
            setImageId(this);
        });

        //监听背景切换
        bgContainer.on('click', '.bgk', function(){
            var src = $(this).find('img').attr('src');
            if ($(this).data('clear')) {
                areaObj.css({
                    backgroundImage: 'none',
                }).data('bgSrc', '');
            } else {
                areaObj.css({
                    backgroundImage: 'url('+ src +')',
                }).data('bgSrc', src);
            }
        }).find('img').each(function(){
            setImageId(this);
        });
        areaObj.data('bgSrc', '');

        //清空操作空间
        $('.clearAreaBtn').click(function(){
            ActionBlock.elementObj.remove();
            hmContainer.find('.change-img').removeClass('active');
        });

        //放大操作空间
        $('.inAreaBtn').click(function(){
            areaObj.css('zoom', Zoom.in());
        }).mousedown(function(e){
            if (3 == e.which) {
                areaObj.css('zoom', Zoom.max());
            }
        }).bind("contextmenu", function(){
            return false;
        });

        //缩小操作空间
        var outAreaBtn = $('.outAreaBtn');
        outAreaBtn.click(function(){
            areaObj.css('zoom', Zoom.out());
        }).mousedown(function(e){
            if (3 == e.which) {
                areaObj.css('zoom', Zoom.min());
            }
        }).bind("contextmenu", function(){
            return false;
        });

        //倍率放大逻辑
        var Zoom = (function(prevBtnObj){
            var maxZoom = 2, minZoom = .1,
                zoom = 1, cancelBtn = null;
            function toZoom (type) {
                if (type === true) {
                    zoom += .1;
                } else if (type === false) {
                    zoom -= .1;
                } else {
                    zoom = type
                }
                if (zoom > maxZoom) {
                    zoom = maxZoom;
                } else if (zoom < minZoom) {
                    zoom = minZoom;
                }
                toggleCancelBtn(zoom != 1);
                return zoom;
            };
            function toggleCancelBtn (type) {
                if (!cancelBtn) {
                    cancelBtn = $(doc.createElement('span'));
                    cancelBtn.addClass('pre-c1');
                    cancelBtn.html('<img class="cancelZoomBtn" src="img/cexiao.png">');
                }
                if (type) {
                    if (prevBtnObj.parent().find(cancelBtn).length == 0) {
                        prevBtnObj.after(cancelBtn);
                        cancelBtn.find('img').click(function(){
                            toZoom(1);
                        });
                    }
                } else {
                    cancelBtn.remove();
                    areaObj.css('zoom', zoom);
                }
            };
            return {
                in: function(){ return toZoom(true) },
                out: function(){ return toZoom(false) },
                max: function(){ return toZoom(maxZoom) },
                min: function(){ return toZoom(minZoom) },
            };
        }(outAreaBtn.parent()));

        //鼠标位置记录
        var areaOffset = areaObj.offset();
        areaObj.mousemove(function(evt){
            var xy = getCoordinateByEvent(evt);
            $('.coordinate span').text(' x: '+ xy[0] +' y: '+ xy[1]);
        });
        function getCoordinateByEvent (evt) {
            //new goog.math.Coordinate();
            return [evt.pageX - areaOffset.left, evt.pageY - areaOffset.top];
        };

        //上传操作功能
        (function(){
            var upload_type = null;
            var uploadCore = new UploadsCore({
                    debug: 1,
                    inputId: 'uploadcore-input',
                    fileType: ['image'],
                    uploadURL: '{% url "mrc:upload_file" %}',
                    fileSuffix: {'image':['png', 'jpg', 'jpeg']},
                    csrftoken:csrftoken,
                    initpostBeforeCallback: function (file) {
                        //初始化上传前回调
                        return {
                            postData: {
                                upload_type: upload_type,
                                file_name: file.name,
                                file_type: file.type,
                            }
                        };
                    },
                    getMd5ingCallback: function (file, loaded, total) {
                        //获取md5中回调
                    },
                    waitingCallback: function (data) {
                        //等待上传中回调
                    },
                    startingCallback: function (data) {
                        //开始上传中回调
                    },
                    progressCallback: function (data) {
                        //上传传输中回调
                    },
                    successCallback: function (data) {
                        //上传成功后回调
                        data = data.response;
                        switch (data.upload_type) {
                            case 'background':
                                /*createBackground(data.url);*/ break;
                            case 'human':
                                /*createHuman(data.url);*/ break;
                            default:
                                return TOOL.error('文件上传出错！');
                        }
                        TOOL.successMsg('上传成功！');
                    },
                    failCallback: function (data) {
                        //上传失败后回调
                        TOOL.error('上传失败！');
                    },
                    endedCallback: function (data) {
                        //结束上传后回调
                    },
                    errorCallback: function (data) {
                        //失败后回调
                    },
                }),
                input = $('#uploadcore-input');
            {#$('.myUploads').click(function(){#}
            {#    var type = $(this).data('type');#}
            {#    upload_type = type;#}
            {#    input.click();#}
            {#{).css({#}
            {#    cursor: 'pointer',#}
            {#{);#}
        }());

        //读取列表功能
        (function(){
            $('.openLibrary').click(function(){
                var type = $(this).data('type');
                switch (type) {
                    case 'background': break;
                    case 'human': break;
                    default: return TOOL.error('读取文件列表出错！');
                }
                $.ajax({
                    url: '{% url "mrc:get_images" %}?type=' + type,
                    success: function(data){
                        var obj = $(doc.createElement('div'));
                        obj.html(data);
                        obj = obj.html(obj.find('ul'));
                        layer.open({
                            type: 1,
                            shadeClose: true,
                            area: ['465px', '380px'], //宽高
                            content: obj.html(),
                            title: '选择' + (type=='background' ? '背景' : '人物'),
                            success: function(layero, index){
                                switch (type) {
                                    case 'background':
                                        var callback = 'createBackground'; break;
                                    case 'human':
                                        var callback = 'createHuman'; break;
                                }
                                layero.find('ul').attr('id', 'images-list');
                                layero.find('li>a').each(function(){
                                    var src = $(this).attr('href');
                                    $(this).attr('href', 'javascript:'+ callback +'(\''+ src +'\');layer.close('+ index +');');
                                    $(this).html('').css({
                                        backgroundImage: 'url('+src+')',
                                    });
                                });
                            },
                            end: function(layero){
                                switch (type) {
                                    case 'background':
                                        var obj = bgContainer; break;
                                    case 'human':
                                        var obj = hmContainer; break;
                                }
                                obj.animate({
                                    scrollTop: obj[0].scrollHeight,
                                }, 300);
                            },
                        });
                    },
                    error: function(){
                        TOOL.errorMsg('读取文件列表出错！');
                    },
                });
            }).css({
                cursor: 'pointer',
            });
        }());

        //创建背景
        W.createBackground = function (url) {
            if (hasBgid(url)) {
                return false;
            }
            var obj = $(doc.createElement('div'));
            obj.addClass('bgk');
            obj.html('<img src="'+ url +'"><p>背景'+ (bgContainer.find('.bgk:last').index()+2) +'</p>');
            bgContainer.append(obj);
            setImageId(obj.find('img'));
            return obj;
        };

        //创建人物
        W.createHuman = function (url) {
            if (hasHmid(url)) {
                return false;
            }
            var obj = $(doc.createElement('div'));
            obj.addClass('change-img');
            obj.html('<img src="'+ url +'">');
            hmContainer.append(obj);
            setImageId(obj.find('img'));
            ActionBlock.Images.set(url);
            return obj;
        };

        //创建图片唯一Id
        function getImageId (src) {
            return SparkMD5.hash(src.split('/').pop());
        };
        function setImageId (obj) {
            obj = $(obj);
            obj.attr('data-id', getImageId(obj.attr('src')));
        };
        function hasHmid (src) {
            var nowId = getImageId(src);
            return hmContainer.find('img[data-id="'+ nowId +'"]').length > 0;
        };
        function hasBgid (src) {
            var nowId = getImageId(src);
            return bgContainer.find('img[data-id="'+ nowId +'"]').length > 0;
        };

        //获取保存配置
        W.getSaveConfig = function (string) {
            var config = {
                backgrounds: getBackgroundImgsrc(),
                humans: getHumanImgsrc(),
                currentBg: areaObj.data('bgSrc'),
                currentHm: ActionBlock.elementObj.find('img').attr('src'),
            };
            return string ? TOOL.jsonStrify(config) : config;
        };
        function getHumanImgsrc () {
            var humans = [];
            hmContainer.find('img').each(function(){
                humans.push($(this).attr('src'));
            });
            return humans;
        };
        function getBackgroundImgsrc () {
            var backgrounds = [];
            bgContainer.find('img').each(function(){
                if ($(this).parent().data('clear')) {
                    return true;
                }
                backgrounds.push($(this).attr('src'));
            });
            return backgrounds;
        };

        //使用配置进行初始化
        W.initByConfig = function (config, string) {
            if (string) {
                config = TOOL.jsonParse(config);
            }
            config = config || {};
            initHumanImage(config.humans);
            initBackgroundImage(config.backgrounds);
            setTimeout(function(){
                initCurrentHm(config.currentHm);
                initCurrentBg(config.currentBg);
            }, 100);
        };
        function initHumanImage (humans) {
            hmContainer.find('img').not('[data-init="true"]').parent().remove();
            $.each(humans, function(key, src){
                var obj = createHuman(src);
                if (obj) {
                    obj.find('img').on('error', function(){
                        if (ActionBlock.elementObj.find('img').attr('src') == $(this).attr('src')) {
                            hmContainer.find('img[data-init]').first().click();
                        }
                        obj.remove();
                    });
                }
            });
        };
        function initBackgroundImage (backgrounds) {
            bgContainer.find('img').not('[data-init="true"]').parent().remove();
            $.each(backgrounds, function(key, src){
                var obj = createBackground(src);
                if (obj) {
                    obj.find('img').on('error', function(){
                        obj.remove();
                    });
                }
            });
        };
        function initCurrentHm (hm) {
            if (!hm) {
                return false;
            }
            hm = getImageId(hm);
            hmContainer.find('img[data-id="'+ hm +'"]').click()
        };
        function initCurrentBg (bg) {
            if (!bg) {
                return false;
            }
            bg = getImageId(bg);
            bgContainer.find('img[data-id="'+ bg +'"]').click();
        };

        //放大|缩小操作区域
        var maxSpaceWin = null;
        $('.pre-img-head .icon-1 img').click(function(){
            if ($(this).data('ismax')) {
                layer.close(maxSpaceWin);
            } else {
                openMaxSpace($(this));
            }
        });
        function openMaxSpace (btn) {
            maxSpaceWin = layer.open({
                type: 1,
                shade: true,
                shadeClose: true,
                closeBtn: 0,  //不显示关闭按钮
                title: false, //不显示标题
                content: $('.pre-img-block'),
                success: function(layero, index){
                    btn.data('ismax', true).attr('src', '{% static "img/suoxiao.png" %}');
                    layero.css({
                        width: '90%',
                        height: '80%',
                    }).find('.layui-layer-content').css({
                        height: '100%',
                    });
                    $(window).resize();
                },
                end: function(){
                    btn.data('ismax', null).attr('src', '{% static "img/fangda.png" %}');
                },
            });
        };


        $("#character_reset").click(function(){
            ActionBlock.isAction();
            ActionBlock.reset();
            ActionBlock.exe_bock_not_reply({"method": "rest_board", "params": ['null']});
            window.blockly_is_run=false;
        });

        function get_blockly_javascript(){
            /*获取积木的javascript代码，返回一个代码执行的函数地址*/
            var javascript_text=Blockly.JavaScript.workspaceToCode(Blockly.mainWorkspace);
            function character_motion (){
                eval(javascript_text);
            }
            console.info(javascript_text);
            return character_motion;
        }
        var check_queue_timer=null;
        window.check_queue=function () {  //检测积木的执行队列是否有item
            var fulfil=ActionBlock.Queue.hasItem();
            if(fulfil){
            }else{
                clearInterval(check_queue_timer);
                window.blockly_is_run=false;   //是否在运行积木的状态
                $('.character_start').find('img').attr('src','{% static 'img/run_blockly_dark.png' %}');
            }
        };

        $(".character_start").click(function(){

            if(window.blockly_is_run==true){
                alert("正在执行积木动作！");
                return;
            }
            var character_motion=get_blockly_javascript();
            upload_online_run_xml(1,"");
            try{
                $('.character_start').find('img').attr('src','{% static 'img/run_blockly_bright.png' %}');
                window.blockly_is_run=true;
                character_motion();
            }
            catch (e){
                window.blockly_is_run=false;
                $('.character_start').find('img').attr('src','{% static 'img/run_blockly_dark.png' %}');
                alert("执行积木命令运动错误，"+e);
            }
            check_queue_timer=window.setInterval("check_queue()",1000);

        });

    }(
        $('#operating-space'),  //操作空间
        $('.hm-container'),     //人物容器
        $('.bg-container'),     //背景容器
        document, window
    ));
</script>

</body>
</html>
